package com.rex.saas.interceptor;

import com.alibaba.fastjson.JSON;
import com.rex.saas.bean.BaseResponse;
import com.rex.saas.config.CustomConfig;
import com.rex.saas.service.AuthCheckService;
import com.rex.saas.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Description 用户认证拦截器
 * @Author dengzaojian
 * @Date 2024/12/18
 * @Version 1.0
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Resource
    AuthCheckService authCheckService;

    @Autowired
    CustomConfig customConfig;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws IOException {
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            log.debug("OPTIONS请求");

            return true; // 不拦截 OPTIONS 请求
        }
        String requestURI = request.getRequestURI();
        String token = request.getHeader("token");
        log.debug("requestURI=" + requestURI);
        log.debug("token=" + token);
        ServletOutputStream outputStream = null;
        try {
            boolean verifyToken = authCheckService.checkToken(token);
            outputStream = null;
            if (!verifyToken) {
                BaseResponse baseResponse = new BaseResponse(401, "Token error", null);
                String returnMsg = JSON.toJSONString(baseResponse);
                outputStream = response.getOutputStream();
                outputStream.print(returnMsg);
                return false;
            }
        } catch (Exception e){
            log.error("### AuthInterceptor preHandle error", e);
            BaseResponse baseResponse = new BaseResponse(401, "Token error", null);
            String returnMsg = JSON.toJSONString(baseResponse);
            outputStream = response.getOutputStream();
            outputStream.print(returnMsg);
            return false;
        }finally {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        }
        return true;
    }
    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
    }
    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) {
    }



}
